package com.hjl.listener;

import com.hjl.entity.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ServivE
 * @version 0.1
 * @className OnLineUsersListener
 * @description
 * @date 2024/7/26 20:02
 * @since jdk11
 */
@WebListener
public class OnLineUsersListener implements ServletContextListener, HttpSessionAttributeListener {
    ServletContext application = null;

    /**
     * 服务器启动时触发
     *
     * @param sce
     */
    public void contextInitialized(ServletContextEvent sce) {
        //创建集合  用于存放在线用户
        List<User> onLineUsers = new ArrayList<User>();
        //创建ServletContext application 对象
        application = sce.getServletContext();
        //将集合存入ServletContext作用域
        application.setAttribute("onLineUsers", onLineUsers);
    }

    public void contextDestroyed(ServletContextEvent sce) {

    }

    /**
     * 有新用户登录的时候触发  第一次调用request.getSession时创建
     *
     * @param hbe
     */
    public void attributeAdded(HttpSessionBindingEvent hbe) {
        //获得当前在线用户
        HttpSession session = hbe.getSession();
        User user = (User) session.getAttribute("user");
        //将用户集合从application作用域中取出来
        List<User> onLineUsers = (List<User>) application.getAttribute("onLineUsers");
        //将新登录用户存入集合
        onLineUsers.add(user);
    }

    /**
     * 将注销用户从集合中移除
     * @param hbe
     */
    public void attributeRemoved(HttpSessionBindingEvent hbe) {
        //获得登录用户
        User user = (User) hbe.getValue();
        //将用户集合从application作用域中取出来
        List<User> onLineUsers = (List<User>) application.getAttribute("onLineUsers");
        //移除
        onLineUsers.remove(user);
    }

    public void attributeReplaced(HttpSessionBindingEvent hbe) {

    }
}
